<template>
  <!--  上传图片-->
  <div class="image">
    <a :href="actionUrl + imageUrl" target="_blank">{{ filenmae }}</a>
    <el-upload
      :action="actionUrl1"
      :show-file-list="false"
      :on-change="handleChange"
      :auto-upload="false"
      class="avatar-uploader"
    >
      <el-button slot="trigger" size="mini" type="primary">{{ $t('btn.file') }}<!--选取文件--></el-button>
    </el-upload>
  </div>
</template>

<script>
import { uploadFile } from '@/api/homePage/business'
import searData from '@/components/Search/mixin'

export default {
  name: 'Index',
  mixins: [searData],
  props: {
    imageUrl: {
      type: String,
      required: true,
      default: ''
    },
    filenmae: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      fileUrl: '',
      actionUrl: '',
      actionUrl1: '/tBdMaterial/insertMaterialDetail', // 后台地址
      openImage: false
    }
  },
  methods: {
    handleChange(file) {
      this.getBase64(file.raw).then(res => {
        this.filenmae = file.name
        uploadFile({ imgUrl: res, fileName: this.filenmae }).then(ev => {
          if (ev.code === 0) {
            this.fileUrl = ev.data
            this.$emit('update:imageUrl', ev.data)
            this.$emit('update:filenmae', this.filenmae)
          } else {
            this.$confirm(res.message, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'error'
            })
          }
        })
      })
    },
    getBase64(file) {
      // 把图片转成base64编码
      return new Promise(function(resolve, reject) {
        const reader = new FileReader()
        let imgResult = ''
        reader.readAsDataURL(file)
        reader.onload = function() {
          imgResult = reader.result
        }
        reader.onerror = function(error) {
          reject(error)
        }
        reader.onloadend = function() {
          resolve(imgResult)
        }
      })
    },
    deleteImg() {
      this.$emit('update:imageUrl', '')
    }
  }
}
</script>

<style scoped lang="scss">
.avatar-uploader {
  @include upLoad;
}
.image{
  position: relative;
  margin: 0 10px 10px;
}
.label {
  width: 150px;
  text-align: right;
  vertical-align: middle;
  float: left;
  font-size: 14px;
  color: #606266;
  line-height: 40px;
  padding: 0 12px 0 0;
  font-weight: 700;
}
.required{
  &:before{
    content: '*';
    color: #F56C6C;
    margin-right: 4px;
  }
}
.avatar-uploader:hover .magnify {
  display: block;
}
.magnify {
  display: none;
  height: 120px;
  width: 120px;
  background-color: rgba(0, 0, 0, 0.4);
  position: absolute;
  top: 0;
  line-height: 120px;
  border-radius: 6px;

  i {
    font-size: 24px;
    color: #fff;
    padding: 0 15px;
  }
}
.preview{
  display: flex;
  justify-content: center;
  align-items: center;
  max-height: 600px;
  img {
    width: auto;
    max-height: 600px;
  }
}
</style>
